<!DOCTYPE html>
<html lang="zh-CN">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>






<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/binblog/img/binblog.ico">
  <link rel="icon" type="image/png" href="/binblog/img/binblog.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="leo-bin">
  <meta name="keywords" content="">
  <title>设计模式之单例模式 - 阿斌的个人博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/binblog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/dracula.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/binblog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/binblog/">&nbsp;<strong>Abin的Blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/binblog/img/6.webp') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-05-31 22:12">
      2020年5月31日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.7k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      30
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-post-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-post-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年7月14日 晚上
                
              </p>
            
            <article class="markdown-body">
              <h1 id="设计模式之单例模式"><a href="#设计模式之单例模式" class="headerlink" title="设计模式之单例模式"></a>设计模式之单例模式</h1><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>在软件设计的道路上，出现了一种叫做设计模式的软件设计方法。</p>
<p>可能很多人都觉得我只要会写代码，功能没问题就行。</p>
<p>但是大家有想过你写好的代码的性能，可塑性，可健壮性，可读性吗？</p>
<p>如果说能够用现有知识实现一个功能，这只能说明你是一个合格的程序员。</p>
<p>但是如果还能够对自己写好的代码进行重构，优化，那么！你就还是一个  <code>程序员</code>。。。</p>
<h2 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h2><p>本次给大家分享最常见的一种设计模式：<strong>单例设计模式</strong>。</p>
<p>为什么说常见呢，因为据网上的统计，光单例设计模式就有<strong>8</strong>种不同的写法！</p>
<p>这里因为本人能力和精力有限，所以只简单介绍<code>5</code>种单例的写法。</p>
<p><strong>1.普通单例模式</strong></p>
<p><strong>2.懒汉式单例模式</strong></p>
<p><strong>3.静态内部类懒汉式单例模式</strong></p>
<p><strong>4.饿汉式单例模式</strong></p>
<p><strong>5.枚举单例模式</strong></p>
<h2 id="单例设计模式介绍"><a href="#单例设计模式介绍" class="headerlink" title="单例设计模式介绍"></a>单例设计模式介绍</h2><p>单例，顾名思义，就是指<strong>一个类只能有一个实例存在</strong>。</p>
<p>为什么要有这种概念的产生呢?</p>
<p>因为在我们的系统开发中，可能会有一种对象需要全局的反复使用。</p>
<p>每次要用到了就创建一个对象，不用了就销毁，很明显，太浪费资源了。</p>
<p>而且，反复的创建对象的开销也不小，由此就诞生了单例模式。</p>
<p>线程池的设计就是一个经典的单例典范。</p>
<p>单例模式需要满足以下三个条件：</p>
<p>1.保证系统全局中一个Class只能有<strong>一个实例</strong>。</p>
<p>2.这个Class必须要对外提供一个获取此单例的<strong>唯一静态方法</strong>。</p>
<p>3.此Class的实例必须要由<strong>自己创建</strong>，不能由除本类之外的类产生。</p>
<p>所以，根据以上的要求，我们只要做到：</p>
<p><strong>1.构造方法私有化。</strong></p>
<p><strong>2.对外提供一个静态获取本实例的方法。</strong></p>
<p><strong>3.本实例由自己创建。</strong></p>
<h2 id="1-普通单例模式"><a href="#1-普通单例模式" class="headerlink" title="1.普通单例模式"></a>1.普通单例模式</h2><p><strong>单例模式的最简单实现</strong></p>
<p>直接看代码：</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Singleton</span></span>&#123;
    <span class="hljs-comment">//1.对外提供的唯一实例</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Singleton singleton;
    
    <span class="hljs-comment">//2.构造函数私有化</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Singleton</span><span class="hljs-params">()</span></span>&#123;
        
    &#125;
    
    <span class="hljs-comment">//3.对外提供获取本实例的唯一方法</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Singleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
            singleton=<span class="hljs-keyword">new</span> Singleton();
        &#125;
        <span class="hljs-keyword">return</span> singleton;
    &#125;
&#125;</code></pre></div>
<p>可以看到的是，因为将构造函数私有化了，所以本实例无法被外部类所调用生成。</p>
<p>要想获取本实例只能通过一个getInstance的静态方法来获取。</p>
<p>而且这个方法在每次获取之前都会判断本实例是否为空，如果为空才会选择创建。</p>
<p>否则直接返回之前创建过的实例，由此来保证实例的全局唯一性。</p>
<p><code>问题：</code></p>
<p>这种写法在<strong>单线程</strong>中没有问题，那要是换成<strong>多线程</strong>呢？</p>
<div class="hljs"><pre><code class="hljs xml">单线程肯定是没问题的，但是在多线程的环境下就会出现单例不唯一的情况！</code></pre></div>
<p>我们可以假设现在有两个线程A,B都想要获取一个实例。他们同时调用getInstance方法。</p>
<p>并且碰巧的是，他们同时都执行到了if判断那里。</p>
<p>所以最终会出现同时都判断出实例为空，那就同时创建一个实例，此时JVM中就会出现<strong>多个实例</strong>！</p>
<p>所以，为了解决单例模式的种种问题，涌现出了好多单例模式的不同写法。</p>
<h2 id="2-懒汉式单例模式"><a href="#2-懒汉式单例模式" class="headerlink" title="2.懒汉式单例模式"></a>2.懒汉式单例模式</h2><p>第一种写法就是懒汉式。</p>
<p>同样的，见名知意，懒汉，就是懒，lazy。</p>
<p>核心思想就是当你要用实例的时候，我再返回一个实例给你，否则我啥都不做。</p>
<p>仔细看过上面的代码你就知道，第一种普通单例模式的写法就是一种懒汉式。</p>
<p>但是这里我们要如何写才能保证单例的唯一性呢？</p>
<p>简单！既然是多线程，我们加锁呗！保证同一时刻只有一个线程调用方法不就行了？</p>
<p>ok，我们就用最简单的加锁方式：<strong>synchronized关键字</strong></p>
<p><strong>修改之后的代码如下：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Singleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-keyword">synchronized</span>(Singleton<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>&#123;
        <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
            singleton=<span class="hljs-keyword">new</span> Singleton();
        &#125;
        <span class="hljs-keyword">return</span> singleton;
    &#125;
&#125;</code></pre></div>
<p>代码很简单对吧，确实这样做的确不会产生什么问题，但是性能呢？还能优化吗？</p>
<p>还能将锁的细粒度细化吗？</p>
<p>可以！我们要锁住的其实不是整个方法体，只要锁会产生线程不安全的代码片段就行了。</p>
<p>这里会产生线程不安全的地方就是那个if逻辑，我们再次修改下代码。</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Singleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
        <span class="hljs-keyword">synchronized</span>(Singleton<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>&#123;
            <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
                singleton=<span class="hljs-keyword">new</span> Singleton();
            &#125;
        &#125;
    &#125;
    <span class="hljs-keyword">return</span> singleton;
&#125;</code></pre></div>
<p>这也是懒汉单例模式的DCL写法（Double Check Lock）</p>
<p>但是，DCL也没什么问题吗？</p>
<p>问题肯定是有的，但是在说问题之前需要引入一个概念：<strong><code>指令重新排序</code></strong></p>
<p>指令重排序：</p>
<p>指令重排序原本指的是在CPU在执行具体的一系列指令之前会对这些指令进行重排序。</p>
<p>因为我们知道人为给出的指令执行顺序可能执行效率不是很好。</p>
<p>所以CPU在最终的执行结果不变的前提下，通过调整某些指令的执行顺序来对指令进行优化。</p>
<p>目的就是为了优化指令的执行顺序（有点像数据库中的SQL优化器）。</p>
<p>同样的的，在JVM中，也有这种机制。</p>
<p>就拿上面那段代码来说：</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Singleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
    <span class="hljs-comment">//1.先判断是否为空</span>
    <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
        <span class="hljs-keyword">synchronized</span>(Singleton<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>&#123;
            <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
                <span class="hljs-comment">//2.初始化一个实例，并赋值给singleton</span>
                singleton=<span class="hljs-keyword">new</span> Singleton();
            &#125;
        &#125;
    &#125;
    <span class="hljs-comment">//3.返回实例的引用</span>
    <span class="hljs-keyword">return</span> singleton;
&#125;</code></pre></div>
<p>这里还需要强调一点，一个对象的产生需要经过几个步骤：</p>
<p>1.加载Class，给对象在堆中分配内存。</p>
<p>2.执行Class的构造函数进行初始化。</p>
<p>3.返回对象的引用地址。</p>
<p>所以，经过JVM的指令重排序，最终的执行顺序可能会变成：</p>
<p>1  -&gt;  3   -&gt;2</p>
<p>因为JVM认为反正你迟早要返回对象的引用地址的，那我先给你返回，给你优化一哈。</p>
<p>但是这样子就有问题了！</p>
<p>还是多线程A，B的环境下。</p>
<p>A经过指令重排序，提前将实例的引用返回了，此时B正好在判断实例是否为空。</p>
<p>很明显，我都拿到引用地址了，当然认为不为空。</p>
<p>所以B就乐乐呵呵的拿到这个半成品实例，并开开心心的去执行业务，DING！</p>
<p>完蛋！直接爆出空指针异常！</p>
<p>那我们如何解决呢？</p>
<p>在JVM中为了防止某些特殊情况下的指令重排序，可以使用volatile关键字来防止指令重排序。</p>
<p>因为volatile可以在<code>volatie</code>变量写的情况下，在写指令之前插入一个内存屏障。</p>
<p>使得其他指令不得排在这个写指令之前。</p>
<p>其实如果我们查看下具体的字节码的话，我们会发现这个volatile实际上就是在写指令完成之后加上了一段指令</p>
<p>这段指令是：lock xxx addl xxx，具体就是像主存发起一个空操作。</p>
<p>但这个空操作会导致此变量重新被刷回主存，所以如果有其他线程正在使用此实例，那就需重新去主存中加载一哈。</p>
<p>这就起到了内存屏障的作用。</p>
<p>所以，我们的最终代码就是：</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LazySingleton</span></span>&#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">volatile</span> LazySingleton singleton;
    
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">LazySingleton</span><span class="hljs-params">()</span></span>&#123;
        
    &#125;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> LazySingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
            <span class="hljs-keyword">synchronized</span>(LazySingleton<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>&#123;
                <span class="hljs-keyword">if</span>(singleton==<span class="hljs-keyword">null</span>)&#123;
                    singleton=<span class="hljs-keyword">new</span> LazySingleton();
                &#125;
            &#125;
        &#125;
        <span class="hljs-keyword">return</span> singleton;
    &#125;
&#125;</code></pre></div>
<h2 id="3-静态内部类懒汉式单例模式"><a href="#3-静态内部类懒汉式单例模式" class="headerlink" title="3.静态内部类懒汉式单例模式"></a>3.静态内部类懒汉式单例模式</h2><p>其实上面那种DLC的懒汉式写法确实比较复杂了，但是学习吗，学无止境。</p>
<p>这里其实还有一种更加简单的懒汉式写法，同样也能保证线程安全。</p>
<p>首先我们可以思考一个问题，什么是静态内部类？</p>
<p>这个简单，静态内部类不就是写在一个类中的静态类吗？有什么问题？</p>
<p>那你能写一个实例出来吗？</p>
<p>ok，没问题，小菜一叠！</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestClass</span></span>&#123;
    
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> TestClass testClass; 
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">TestClass</span><span class="hljs-params">()</span></span>&#123;
        
    &#125;
    <span class="hljs-comment">//静态内部类</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InnerClass</span></span>&#123;
        
    &#125;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
        
    &#125;
&#125;</code></pre></div>
<p>那我继续问你，如果我调用getInstance方法会不会在堆中产生一个InnerClass的对象？</p>
<p>不会，静态类只有在被调用了的时候才会进行初始化。</p>
<p>ok，那我们就将生成实例的方法放在静态内部类中吧！</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LazyHolderSinglton</span></span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">LazyHolderSingleton</span><span class="hljs-params">()</span></span>&#123;
        
    &#125;
    
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LazyHolder</span></span>&#123;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> LazyHolderSingleton singleton=<span class="hljs-keyword">new</span> LazyHolderSingleton();
    &#125;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> LazyHolderSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">return</span> LazyHolder.singleton;
    &#125;
&#125;</code></pre></div>
<p>可以看到，因为实例被修饰成fanal类型，所以实例可以保证只有一个。</p>
<p>不仅如此，JVM为静态类的初始化提供了线程安全的机制，我们也不用操心加锁了。</p>
<h2 id="4-饿汉式单例模式"><a href="#4-饿汉式单例模式" class="headerlink" title="4.饿汉式单例模式"></a>4.饿汉式单例模式</h2><p>根据上面提到的静态内部类的方法，其实我们还可以将实例直接修饰成<strong>静态变量</strong>。</p>
<p>在类被加载的时候就产生一个单例对象。</p>
<p>这种单例模式就叫做<strong>饿汉式单例模式</strong>。</p>
<p><strong>代码如下：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HungrySingleton</span></span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">HungrySingleton</span><span class="hljs-params">()</span></span>&#123;
        
    &#125;
    
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> HungrySingleton singleton=<span class="hljs-keyword">new</span>  HungrySingleton();
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> HungrySingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">return</span> singleton;
    &#125;
&#125;</code></pre></div>
<h2 id="5-枚举单例模式"><a href="#5-枚举单例模式" class="headerlink" title="5.枚举单例模式"></a>5.枚举单例模式</h2><p>至于最后这种枚举类的单例模式就是利用了枚举对象初始化的特点</p>
<p>其实很本质上，枚举类底层还是用的静态的方法。</p>
<p>这里只提供代码，看代码就能明白了，具体的思想和上面差不多</p>
<p><strong>代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EnumSingleton</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">EnumSingleton</span><span class="hljs-params">()</span> </span>&#123;

    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 2.定义一个内部枚举类用来生成本实列，也就是外部类的实例</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">enum</span> Singleton &#123;

        INSTANCE;
        
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> EnumSingleton enumSingleton;

        Singleton() &#123;
            enumSingleton = <span class="hljs-keyword">new</span> EnumSingleton();
        &#125;

        <span class="hljs-function"><span class="hljs-keyword">private</span> EnumSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>&#123;
            <span class="hljs-keyword">return</span> enumSingleton;
        &#125;
    &#125;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> EnumSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> Singleton.INSTANCE.getInstance();
    &#125;
&#125;</code></pre></div>
<h2 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h2><p>可以看到一个简单的单例模式就能扯出这么多知识点，可想而知其他复杂一点的设计模式了。</p>
<p>学习的路上总是会有很多的诱惑，秋招加油！</p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/binblog/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E6%89%8B%E5%86%99%E7%B3%BB%E5%88%97%E4%B9%8B%E6%89%8B%E5%86%99%E4%B8%80%E4%B8%AA%E6%A0%88/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">手写系列之手写一个栈</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8B%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/">
                        <span class="hidden-mobile">设计模式之策略模式</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="https://cdn.staticfile.org/valine/1.4.14/Valine.min.js" ></script>

  <script type="text/javascript">
    var oldLoadVa = window.onload;
    window.onload = function () {
      oldLoadVa && oldLoadVa();

      new Valine({
        el: "#vcomments",
        app_id: "vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz",
        app_key: "v2hMMe4Mzz3mqpy9jwd7qx8B",
        placeholder: "说点什么吧！",
        path: window.location.pathname,
        avatar: "retro",
        meta: ["nick","mail","link"],
        pageSize: "10",
        lang: "zh-CN",
        highlight: true,
        recordIP: false,
        serverURLs: "",
      });
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


    
  <!-- 备案信息 -->
  <div class="beian">
    <a href="http://beian.miit.gov.cn/" target="_blank"
       rel="nofollow noopener">京ICP证123456号</a>
    
      <a
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
        rel="nofollow noopener"
        class="beian-police"
        target="_blank"
      >
        <span class="beian-police-sep">&nbsp;|&nbsp;</span>
        
          <img src="/binblog/img/police_beian.png" srcset="/binblog/img/loading.gif" alt="police-icon" />
        
        <span>京公网安备12345678号</span>
      </a>
     
  </div>


    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/binblog/js/debouncer.js" ></script>
<script  src="/binblog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/binblog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/binblog/js/clipboard-use.js" ></script>



  <script defer>
  (function () {
    // 查询存储的记录
    function getRecord(Counter, target) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({target})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {target, time: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    }

    // 发起自增请求
    function increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    }

    // 构建自增请求体
    function buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "time": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    }

    // 校验是否为有效的 UV
    function validUV() {
      var key = 'LeanCloud_UV_Flag';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    }

    function addCount(Counter) {
      var enableIncr = 'true' === 'true' && window.location.hostname !== 'localhost';
      var getterArr = [];
      var incrArr = [];

      // 请求 PV 并自增
      var pvCtn = document.querySelector('#leancloud-site-pv-container');
      if (pvCtn || enableIncr) {
        var pvGetter = getRecord(Counter, 'site-pv').then((record) => {
          incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-pv');
          if (ele) {
            ele.innerText = record.time + 1;
            if (pvCtn) {
              pvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#leancloud-site-uv-container');
      if (uvCtn || enableIncr) {
        var uvGetter = getRecord(Counter, 'site-uv').then((record) => {
          var vuv = validUV();
          vuv && incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-uv');
          if (ele) {
            ele.innerText = record.time + (vuv ? 1 : 0);
            if (uvCtn) {
              uvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(uvGetter);
      }

      // 如果是文章，请求文章的浏览数，并自增
      if ('true' === 'true') {
        var viewCtn = document.querySelector('#leancloud-post-views-container');
        if (viewCtn || enableIncr) {
          var target = decodeURI('/binblog/2020/05/31/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8B%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/');
          var viewGetter = getRecord(Counter, target).then((record) => {
            incrArr.push(buildIncrement(record.objectId))
            if (viewCtn) {
              var ele = document.querySelector('#leancloud-post-views');
              if (ele) {
                ele.innerText = (record.time || 0) + 1;
                viewCtn.style.display = 'inline';
              }
            }
          });
          getterArr.push(viewGetter);
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && increment(Counter, incrArr);
        })
      }
    }

    var app_id = 'vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz'
    var app_key = 'v2hMMe4Mzz3mqpy9jwd7qx8B'
    var server_url = ''

    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': app_id,
            'X-LC-Key': app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };

      addCount(Counter);
    }

    var api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${ app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(resp => resp.json())
        .then(({api_server}) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>






  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "设计模式之单例模式&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/binblog/js/local-search.js" ></script>
  <script>
    var path = "/binblog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  













  

  

  

  

  

  





<script src="/binblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/binblog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
